package controller

import (
	"fmt"
	"github.com/go-pay/gopay"
	"ksd-social-api/commons/base/controller"
	utils2 "ksd-social-api/utils"
)

type AlipayNativeVipController struct {
	controller.BaseController
	AlipayPayBaseController
}

/**
 * 支付宝支付-会员
 * @author feige
 * @date 2023-12-04
 * @version 1.0
 * @desc
 */
func (web *AlipayNativeVipController) NativePayVip() {
	client, ctx := web.GetAlipayPayClient()
	if nil == client {
		web.FailCodeMsg(901, "支付宝支付初始化失败")
		return
	}

	// 课程业务
	vipId, _ := web.ParseParamUint64("opid")
	userVipVo := userVipService.GetUserVipById(vipId, web.GetSystemId())
	if userVipVo == nil {
		web.FailCodeMsg(901, "支付的用户身份不存在！")
		return
	}

	// 参数map ?
	mattch := map[string]any{}
	mattch["userId"] = web.GetUserId()
	mattch["opid"] = vipId
	mattch["type"] = "vip"
	mattch["price"] = userVipVo.Price

	OutTradeNo := web.GetSnowWorkerIdString(5)
	fmt.Println("阿里支付：OutTradeNo", OutTradeNo)
	//请求参数
	bm := make(gopay.BodyMap)
	bm.Set("subject", userVipVo.Title)
	bm.Set("out_trade_no", fmt.Sprintf("%s_%s_%d_%d", OutTradeNo, "vip", web.GetUserId(), vipId))
	bm.Set("total_amount", userVipVo.Price)
	// 发起交易
	m := map[string]any{}
	// 阿里支付生成支付链接
	aliRsp, err := client.TradePrecreate(ctx, bm)
	if err != nil {
		// 处理错误
		m["url"] = ""
		m["status"] = "fail"
		m["tradeNo"] = ""
	} else {
		// 处理返回结果
		m["url"] = aliRsp.Response.QrCode
		m["tradeNo"] = aliRsp.Response.OutTradeNo
		m["status"] = "success"
	}

	web.Ok(m)
}

/**
 * vip升级
 * @author feige
 * @date 2023-12-04
 * @version 1.0
 * @desc
 */
func (web *AlipayNativeVipController) QueryOrderByVipOutTradeNo() {
	// 获取支付的交易编号
	OutTradeNo := web.GetString("tradeno")
	vipId, _ := web.GetUint64("vipId")
	ptype := web.GetString("type")
	client, ctx := web.GetAlipayPayClient()
	if nil == client {
		web.FailCodeMsg(901, "支付宝支付初始化失败")
		return
	}

	//请求参数
	bm := make(gopay.BodyMap)
	bm.Set("out_trade_no", OutTradeNo)
	aliRsp, err := client.TradeQuery(ctx, bm)
	if err != nil {
		web.FailCodeMsg(901, "支付宝支付初始化失败")
		return
	}

	response := aliRsp.Response
	// TRADE_FINISHED
	tmp := make(map[string]interface{})
	if response.TradeStatus == "TRADE_SUCCESS" {
		if ptype == "vip" {
			isBuyFlag := userBuyVipService.CountUserBuyVipByOutTradeNo(OutTradeNo, web.GetSystemId())
			if isBuyFlag > 0 {
				web.FailCodeMsg(902, "订单已经创建")
				return
			}
			// 订单保存落库
			userBuyVipService.SaveUserVipOrder(
				response.OutTradeNo, response.TradeNo, utils2.StructToJson(response), 2, "支付宝", response.TotalAmount,
				web.GetUserId(), vipId, web.GetSystemId(), web.GetSystemName())
		}
		//支付宝支付回调返回特殊处理，Flag = 40
		tmp["code"] = "SUCCESS"
		tmp["message"] = "成功"
		web.Ok(tmp)
	} else {
		web.FailCodeMsg(901, "fail")
	}
}
